package bitcat.chuenyee.dao.controller

import bitcat.chuenyee.dao.mapper.DynamicCrudMapper
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/dynamic")
class DynamicCrudController(private val mapper: DynamicCrudMapper) {

    @PostMapping("/insert")
    fun insert(@RequestParam table: String, @RequestBody data: Map<String, Any>): String {
        val params = mutableMapOf<String, Any>("table" to table)
        params.putAll(data)
        params["data"] = data
        mapper.insert(params)
        return "Insert success"
    }

    @PostMapping("/select")
    fun select(
        @RequestParam table: String,
        @RequestBody conditions: Map<String, Any>?
    ): List<Map<String, Any>> {
        val params = mutableMapOf<String, Any>("table" to table)
        if (conditions != null) params["conditions"] = conditions
        return mapper.select(params)
    }

    @PutMapping("/update")
    fun updateById(
        @RequestParam table: String,
        @RequestBody params: Map<String, Any>
    ): String {
        // 将不可变 Map 转成 MutableMap
        val mutableParams = params.toMutableMap()
        mutableParams["table"] = table
        mapper.update(mutableParams)
        return "Update success"
    }

    @DeleteMapping("/delete")
    fun delete(
        @RequestParam table: String,
        @RequestBody conditions: Map<String, Any>?
    ): String {
        val params = mutableMapOf<String, Any>("table" to table)
        if (conditions != null) params["conditions"] = conditions
        mapper.delete(params)
        return "Delete success"
    }

}
